package com.speakerssphere.extension.handlers;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.smartfoxserver.bitswarm.sessions.ISession;
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.entities.data.SFSArray;
import com.smartfoxserver.v2.exceptions.SFSErrorCode;
import com.smartfoxserver.v2.exceptions.SFSErrorData;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.exceptions.SFSLoginException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;
import com.smartfoxserver.v2.extensions.ExtensionLogLevel;

public class LoginEventHandler extends BaseServerEventHandler {

	@Override
	public void handleServerEvent(ISFSEvent event) throws SFSException {
		String username = (String) event.getParameter(SFSEventParam.LOGIN_NAME);
		String password = (String) event
				.getParameter(SFSEventParam.LOGIN_PASSWORD);

		//if not guest
		if (!"".equals(username)) {

			// make sure there is a password before you try to use the
			// checkSecurePassword function
			if (password.equals("")) {
				SFSErrorData data = new SFSErrorData(
						SFSErrorCode.LOGIN_BAD_PASSWORD);
				data.addParameter(username);
				throw new SFSLoginException("You must enter a password.", data);
			}

			ISession session = (ISession) event
					.getParameter(SFSEventParam.SESSION);

			try {
				// get a connection to the database
				Connection conn = getParentExtension().getParentZone()
						.getDBManager().getConnection();

				// This will strip potential SQL injections
				PreparedStatement sql = conn
						.prepareStatement("SELECT userid, password FROM dbo.users WHERE username = ?");
				sql.setString(1, username);

				// Obtain ResultSet
				ResultSet result = sql.executeQuery();

				// Put the result into an SFSobject array
				/*
				 * SFSArray rows = SFSArray.newFromResultSet(result);
				 * System.out.println(rows.toString()); if(rows.size() == 0){
				 * SFSErrorData data = new
				 * SFSErrorData(SFSErrorCode.LOGIN_BAD_USERNAME);
				 * data.addParameter(username); throw new
				 * SFSLoginException("User doesn't exist.", data); }
				 */

				// SFS always encrypts passwords before sending them so you need
				// to
				// decrypt the password
				// received from the database and compare that to what they
				// entered
				// in flash

				// if (!getApi().checkSecurePassword(session,
				// rows.getSFSObject(0).getUtfString("password"), password))
				// if(!row.getSFSObject(0).getUtfString("password").equals(password))

				if (!result.next()) {
					throw new SFSLoginException(
							"Login or password is incorrect");
				} else {
					String dbpass = result.getString("password");
					trace("dbpass: " + dbpass + "; pass: " + password);
					if (!getApi()
							.checkSecurePassword(session, dbpass, password)) {
						throw new SFSLoginException(
								"Login or password is incorrect");
					}
				}

				// make sure you close the database connection when you're done
				// with
				// it, especially if you've
				// set a low number of maximum connections
				conn.close();

				// at this point you could trigger an joinRoom request if you
				// wanted
				// to, otherwise
				// this will return success to your LOGIN event listener
				trace("Login successful, joining room!");

			} catch (SQLException e) {
				e.printStackTrace();
				trace(ExtensionLogLevel.WARN, " SQL Failed: " + e.toString());
				throw new SFSLoginException("Login failed for user: "
						+ username + "; Exception: " + e.getMessage());
			} catch (Exception e) {
				trace(ExtensionLogLevel.WARN, " Exception: " + e.toString());

				SFSErrorData data = new SFSErrorData(
						SFSErrorCode.LOGIN_ALREADY_LOGGED);
				data.addParameter(username);
				e.printStackTrace();
				throw new SFSLoginException("Login failed for user: "
						+ username + "; Exception: " + e.getMessage());
			}
		}
	}

}
